<?php

namespace app\home\controller;
use AlipayOauthService;
use QC;
use think\Controller;
use think\cache\driver\Memcached;
class Login extends Controller
{
	# 登录页面展示
	public function index(){
		if(session("?user_info")){
			$this->success("已登录","index/index");
		}
		$this->view->engine->layout(false);
		return view("login/login");
	}
	# 注册页面展示
	public function register(){
		$this->view->engine->layout(false);
		return view("login/register");
	}
	# 发送短信验证码接口
	public function sendcode(){
		# 接收数据
		$phone = input("phone");
		# 数据检测
		if(!preg_match("/^1[3-9]\d{9}$/",$phone)){
			return ["status" => 400,"msg" => "电话号码格式错误"];
		}
		# 判断他发送的时间是否小于60秒，如果小于那就是发送太频繁
		$time = cache("user_time_" . $phone)?:0;
		if(time() - $time < 60){
			return ["status" => 402,"msg" => "发送信息太频繁"];
		}
		# 数据处理
		# 生成随机数据
		$code = mt_rand(1000,9999);
		$msg = "【创信】您的验证码是" . $code . ",三分钟内有效";
		$result = exists_sendcode($phone,$msg);
		$result = true;
		if($result){
			# 返回数据
			# 记录缓存验证码，后期做表单验证使用
			cache("user_code_".$phone,$code,180);
			# 记录缓存时间
			cache("user_time_".$phone,time(),180);
			# 返回数据
			return ["status" => 200,"msg" => "发送成功", "data" => $code];
		}else{
			# 返回数据
			return ["status" => 401,"msg" => "发送失败"];
		}
		
	}
	# 手机号注册
	public function phone(){
		# 接收数据
		$params = input();
		# 数据检测
		$validate = $this->validate($params,[
			"phone|电话号码" => "require|regex:1[3-9]\d{9}|unique:user,phone",
			"password|密码" => "require|length:6,18|confirm:repassword",
			"code|验证码" => "require",
		]);
		if($validate !== true){
			$this->error($validate);
		}
		# 获取验证码
		$code = cache("user_code_" . $params["phone"]);
		if($params["code"] != $code){
			$this->error("验证码错误");
		}
		# 使用缓存过期
		cache("user_code_" . $params["phone"],null);
		cache("user_time_" . $params["phone"],null);
		# 数据处理
		$params["nickname"] = exists_phone($params["phone"]);
		$params["password"] = jiami_password($params["password"]);
		\app\common\model\User::create($params, true);
		// $find = \app\common\model\User::find($data["id"]);
		# 返回数据
		return $this->success("注册成功","login/index");
		
	}
	# qq登录 关联手机号
    public function qqcallback1(){
	    # 引入qq扩展里面的api的入口文件
        require_once("E:/tpshop/public/plugins/qq/Connect2.1/API/qqConnectAPI.php");
        $qc = new \QC();
        # 获取access_token
        $access_token = $qc->qq_callback(); # access_token
        # 获取open_id
        $open_id = $qc->get_openid(); # open_id
        # 第一个参数是接口调用临时授权码 第二个中open_id唯一标识
        $pc = new \QC($access_token,$open_id);
        # 获取qq的返回值
        $info = $pc->get_user_info();
        # 根据openId和open_type查询数据
        $openUser = \app\common\model\OpenUser::where("open_type","qq")->where("openid",$open_id)->find();
        # 判断是否已经关联过用户，判断他是否能够查询到一条数据同时数据里面的user_id存在
        if($openUser && empty($openUser["user_id"])){
            #存在就代表着已经关联过了就直接登录
            $user = \app\common\model\User::find($openUser["user_id"]);
            # 修改数据单个
            $user->nickname = $info["nickname"];
            # 重新保存
            $user->save();
            # 设置登录标识
            session("user_info",$user->toArray());
            $this->success("登录成功","home/index/index");
        }
        if(!$openUser){
            # 没有关联过添加一条新数据
            $openUser = \app\common\model\OpenUser::create(["open_type" => "qq","openid"=>$open_id],true);
        }
        session("open_user_id",$openUser["id"]);
        session("nickname",$info["nickname"]);
        $this->success("qq登录成功，请绑定手机号","home/login/index");
    }
    #qq登录 不关联手机号 直接登录
    public function qqcallback(){
        # 引入qq扩展里面的api的入口文件
        require_once("E:/tpshop/public/plugins/qq/Connect2.1/API/qqConnectAPI.php");
        $qc = new \QC();
        # 获取access_token
        $access_token = $qc->qq_callback(); # access_token
        # 获取open_id
        $open_id = $qc->get_openid(); # open_id
        # 第一个参数是接口调用临时授权码 第二个中open_id唯一标识
        $pc = new \QC($access_token,$open_id);
        # 获取qq的返回值
        $info = $pc->get_user_info();
        # 根据openId和open_type查询数据
        $user = \app\common\model\User::where("open_type","qq")->where("openid",$open_id)->find();
        # 判断是否查询到一条用户，如果有那就是已经登录过了，就直接登录 修改一下nickname姓名就可以了
        if($user){
            # 修改nickname
            $user->nickname = $info["nickname"];
            $user->save();
        }else{
            # 没有登录过创建一个新的用户
            \app\common\model\User::create(["open_type" => "qq","openid"=>$open_id,"nickname" => $info["nickname"]],true);
        }
        $user = \app\common\model\User::where("open_type","qq")->where("openid",$open_id)->find();
        session("user_info",$user->toArray());
        $this->success("登录成功，正在跳转请稍等。。。","home/index/index");
    }
    # 支付宝登录 不关联手机号
    public function alicallback1(){
        require_once("E:/tpshop/public/plugins/alipay/oauth/service/AlipayOauthService.php");
        require_once("E:/tpshop/public/plugins/alipay/oauth/config.php");
        $aop = new \AlipayOauthService($config);
        # 获取auth_code
        $auth_code = $aop->auth_code();
        # 获取access_token
        $access_token = $aop->get_token();
        # 获取用户信息
        $info = $aop->get_user_info();
        $openid = $info["user_id"];
        $user = \app\common\model\User::where("open_type" , "alipay")->where("openid",$openid)->find();
        if($user){
            $user->nickname = $info["nick_name"] ?? $info["id"];
            $user->save();
        }else{
            \app\common\model\User::create(["open_type" => "alipay","openid" => $openid,"nickname" => $info["nick_name"] ?? $info["id"]],true);
        }
        $user = \app\common\model\User::where("open_type","alipay")->where("openid",$openid)->find();
        session("user_info",$user->toArray());
        $this->success("支付宝不关联手机号登录成功","home/index/index");
    }
    # 支付宝登录 关联手机号
    public function alicallback(){
        //引入必要的文件
        require_once './plugins/alipay/oauth/config.php';
        require_once './plugins/alipay/oauth/service/AlipayOauthService.php';
        //实例化AlipayOauthService
        $aop = new \AlipayOauthService($config);
        # 获取auth_code
        $auth_code = $aop->auth_code();
        # 获取access_token
        $access_token = $aop->get_token($auth_code);
        # 获取用户信息
        $info = $aop->get_user_info($access_token);
        if(!empty($info)){
            $this->error("数据错误，请重新登录");
        }
        $openid = $info["user_id"];
        $find = \app\common\model\OpenUser::where("open_type","alipay")->where("openid",$openid)->find();
        if($find && empty($find["user_id"])){
            $user = \app\common\model\User::find(["id" => $openid]);
            $user->nickname = $info["nick_name"];
            $user->save();
            # 设置登录标识
            session("user_info",$user->toArray());
            $this->success("支付宝登录成功","home/index/index");
        }
        if(!$find){
            $open_user = \app\common\model\OpenUser::create(["open_type" => "alipay","openid" => $openid],true);
        }
        session("nickname",$info["nick_name"]);
        session("open_user_id",$open_user["id"]);
        $this->success("支付宝登录成功，正在跳转登录页面绑定手机号","home/login/index");
    }

	# 登录
	public function login(){
		# 接收参数
		$params = input();
		# 参数检测
		$validata = $this->validate($params,[
			"username|用户名" => "require",
			"password|密码" => "require",
		]);
		if($validata !== true){
			$this->error($validata);
		}
		# 数据处理
		# 进行密码加密
		$params["password"] = jiami_password($params["password"]);
		# 根据传入的名称查询一条数据
		$user = \app\common\model\User::where(function($query)use($params){
			$query->where("phone",$params["username"])->whereOr("email",$params["username"]);
		})->where("password",$params["password"])->find();
		# 判断他是否有查询到数据，如果有那就是正确的用户名密码，如果没有那就是错误的 有为true 没有为false
		if($user){
			# 返回
            $open_user_id = session("open_user_id");
            # qq登录判断
            # 判断session里面是否存在open_user_id，如果存在那就修改到open_user表的数据把user_id添加到里面
            if($open_user_id){
                $open_user = \app\common\model\OpenUser::update(["user_id" => $user["id"]],["id" => $open_user_id],true);
                session("open_user_id",null);
            }
            $nickname = session("nickname");
            if($nickname){
                \app\common\model\User::update(["nickname" => $nickname],["id" =>$open_user_id],true);
                session("nickname",null);
            }
			# 存储session
			session("user_info",$user->toArray());
//            cache("user_info",$user->toArray());
			\app\home\logic\CartLogic::cookieSql();
			# 返回跳转页面
			# 从session中获取到请求路径
			$url = session("url_data")?:"index/index";
			return $this->success("登录成功",$url);
		}else{
			# 返回错误提示
			$this->error("密码或用户名错误");
		}
		
	}
	# 退出登录
    public function logout(){
    	# 清空session
    	session(null);
    	# 跳转页面
    	return $this->redirect("home/login/index");
    }
}
